<template>
    <div>
        <el-page-header content="编辑产品" title="产品管理" @back="handleBack" />
        <el-form ref="productFormRef" :model="productForm" :rules="productFormRules" label-width="120px" class="demo-ruleForm">
            <el-form-item label="产品名称" prop="title">
                <el-input v-model="productForm.title" />
            </el-form-item>
            <el-form-item label="产品简要描述" prop="introduction">
                <el-input v-model="productForm.introduction" />
            </el-form-item>
            <el-form-item label="产品详细描述" prop="detail">
                <el-input v-model="productForm.detail" />
            </el-form-item>
            <el-form-item label="内容" prop="cover">
                <Upload :avatar="productForm.cover" @kerwinChange="handleChangeImg" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)" size="large">更新产品</el-button>
            </el-form-item>
        </el-form>
    </div>
</template> 


<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import upload from '@/util/upload'
import Upload from '@/components/upload/Upload'
import axios from 'axios';
import { useRouter, useRoute } from 'vue-router';
const router = useRouter()
const route = useRoute()

const productFormRef = ref()
const productForm = reactive({
    title: '',
    introduction: '',
    detail: '',
    cover: '',
    file: null
})
const productFormRules = reactive({
    title: [
        { required: true, message: '请输入产品名称', trigger: 'blur' },
    ],
    introduction: [
        { required: true, message: '请输入产品简要描述', trigger: 'blur' },
    ],
    detail: [
        { required: true, message: '请输入产品详细描述', trigger: 'blur' },
    ],
    cover: [
        { required: true, message: '请上传产品图片', trigger: 'blur' },
    ],
})


// // 每次选择完图片后的回调
const handleChangeImg = (file) => {
    productForm.cover = URL.createObjectURL(file)
    productForm.file = file
}

const submitForm = () => {
    productFormRef.value.validate(async valid => {
        if (valid) {
            console.log(productForm)
            // 后台通道
            let res = await upload('/adminapi/product/list', productForm)
            console.log(res)
            if (res.data.ActionType == 'ok') {
                ElMessage.success('更新成功')
                router.back()
            }
        }
    })
}

const handleBack = () => {
    router.back()
}


onMounted(async () => {
    getData()
})

const getData = async () => {
    console.log(route.params.id)
    const res = await axios.get(`/adminapi/product/list/${route.params.id}`)
    console.log(res.data.data[0])
    Object.assign(productForm, res.data.data[0])
}

</script>

<style lang="scss" scoped>
.el-form {
    margin-top: 50px;
}
</style>